package com.gientech.controller;
import java.net.URI;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class ConsulConsumerController {
    @Resource
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

    public ConsulConsumerController() {
    }

    @GetMapping({"/consumerA"})
    public String testConsumer() {
        List<ServiceInstance> instances = this.discoveryClient.getInstances("producerA");
        ServiceInstance serviceInstance = (ServiceInstance)instances.get(0);
        URI uri = serviceInstance.getUri();
        String targetUrl = uri + "/producerA";
        System.out.println(targetUrl);
        String rst = (String)this.restTemplate.getForObject(targetUrl, String.class, new Object[0]);
        return "consumer : " + rst;
    }

    @GetMapping({"consumerB"})
    public String test() {
        List<ServiceInstance> instances = this.discoveryClient.getInstances("producerA");
        ServiceInstance serviceInstance = (ServiceInstance)instances.get(0);
        URI uri = serviceInstance.getUri();
        String targetUrl = uri + "/pro-test";
        String rst = (String)this.restTemplate.getForObject(targetUrl, String.class, new Object[0]);
        return "consumer : " + rst;
    }
}
